package com.chat.net;

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer {
    private static final Map<Integer, PrintWriter> clients = new HashMap<>();

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9000);
        System.out.println("服务器已启动，等待连接...");
        while(true) {
            Socket socket = serverSocket.accept();
            new Thread(new ClientHandler(socket)).start();
        }
    }

    static class ClientHandler implements Runnable {
        private Socket socket;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            Integer userId = null;
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
                String line;
                userId = null;
                // 第一次收到的是用户ID
                if ((line = in.readLine()) != null) {
                    userId = Integer.parseInt(line.trim());
                    synchronized (clients) {
                        clients.put(userId, out);
                    }
                    System.out.println("用户 " + userId + " 已上线");
                }

                while ((line = in.readLine()) != null) {
                    String[] parts = line.split(":");
                    int toUserId = Integer.parseInt(parts[0]);
                    String message = parts[1];
                    System.out.println("转发消息：" + userId + " -> " + toUserId + ": " + message);
                    PrintWriter writer = clients.get(toUserId);
                    if (writer != null) {
                        writer.println(userId + ":" + message);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (userId != null) {
                    synchronized (clients) {
                        clients.remove(userId);
                    }
                    System.out.println("用户 " + userId + " 已下线");
                }
            }
        }
    }
}
